<template>
  <div class="contain">
    <input class="search_box" type="text" placeholder="请输入城市名或拼音" v-model="keyword" />

    <div class="search-content" ref="wrapper" v-show="keyword">
      <div class="wrapper">
        <div
          class="item border-bottom"
          v-for="item in list"
          :key="item.id"
          @click="handleCity(item.name)"
        >{{item.name}}</div>
        <div class="nodata border-bottom" v-show="nodata">没有找到匹配数据</div>
      </div>
    </div>
  </div>
</template>

<script>
import Bscroll from "better-scroll";
export default {
  name: "Search",
  props: ["cities"],
  data() {
    return {
      keyword: "",
      list: [],
      timer: null,
    };
  },
  mounted() {
    this.scroll = new Bscroll(this.$refs.wrapper,{
      click: true
    });
  },
  methods: {
    handleCity(city) {
      this.$store.commit("changeCity", city);
      this.keyword = null;
      this.$router.push('/')
    },
  },
  computed: {
    nodata() {
      return !this.list.length;
    },
  },
  watch: {
    keyword() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (!this.keyword) {
        this.list = [];
        return;
      }
      this.timer = setTimeout(() => {
        const result = [];
        for (let i in this.cities) {
          // console.log(item);
          this.cities[i].forEach((value) => {
            if (
              value.spell.indexOf(this.keyword) > -1 ||
              value.name.indexOf(this.keyword) > -1
            ) {
              // console.log(value);
              result.push(value);
            }
          });
          //
          // }
        }
        this.list = result;
      }, 100);
    },
  },
};
</script>

<style lang="stylus" scoped>
@import '~style/varibles.styl'

.contain
  height 0.72rem
  background-color $bgColor

  // padding .2rem .2rem
  .search_box
    margin 0.1rem 0.2rem
    padding-left 0.1rem
    padding-right 0.1rem
    border-radius 0.1rem
    width 6.5rem
    height 0.52rem
    color #666666
    text-align center

  .search-content
    z-index 1
    overflow hidden
    position absolute
    top 1.58rem
    left 0
    right 0
    bottom 0
    background-color #eeeeee

    .item, .nodata
      padding 0.1rem 0.2rem
      text-align left
      // border .01rem solid #ffffff
      background-color #dddddd
</style>